package net.zxjava.gateway.filters;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import net.zxjava.gateway.bean.Permission;

public class PermissionFilter extends ZuulFilter {
	private static final Logger logger = LoggerFactory.getLogger(PermissionFilter.class);
	private static final String PREFIX = "/zxjava-gateway";
	private static final String SESSIONID = "sessionId";

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public Object run() {

		RequestContext ctx = RequestContext.getCurrentContext();

		HttpServletRequest request = ctx.getRequest();

		Cookie[] cookies = ctx.getRequest().getCookies();
		String sessionId = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (StringUtils.equals(cookie.getName(), SESSIONID)) {
					sessionId = cookie.getValue();
				}
			}
		}

		Integer userId = sessionId.hashCode();

		ctx.set("accountId", userId);

		String resUrl = request.getServletPath();

		if (!StringUtils.startsWithIgnoreCase(resUrl, PREFIX)) {
			return null;
		}

		resUrl = resUrl.substring(PREFIX.length(), resUrl.length());

		logger.info("request url {}", resUrl);

		List<Permission> resourcesList = new ArrayList<>();// TODO

		for (Permission permission : resourcesList) {
			if (permission.getResurl() != null && permission.getResurl().equals(resUrl)) {
				ctx.setSendZuulResponse(true);
				ctx.set("isSuccess", true);
				return null;
			}
		}

		if (userId == 2) {
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(200);
			ctx.setResponseBody(JSONObject.toJSONString("access token is empty"));
			return null;
		}

		ctx.setSendZuulResponse(true);
		ctx.set("isSuccess", true);
		return null;

	}

}
